<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, watch, computed, reactive } from 'vue'
import { TableData } from '@/api/table/types'
import { Descriptions, DescriptionsSchema } from '@/components/Descriptions'
import { useI18n } from '@/hooks/web/useI18n'

const { t } = useI18n()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<TableData>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<Array<DescriptionsSchema>>,
    default: () => []
  }
})

const formSchema = reactive<FormSchema[]>([
  {
    field: 'borrowQuantity',
    label: t('borrowTable.borrowQuantity'),
    component: 'InputNumber'
  },
  {
    field: 'preReturnTime',
    label: t('borrowTable.preReturnTime'),
    component: 'DatePicker',
    componentProps: {
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss'
    }
  }
])

const formattedData = computed(() => {
  if (!props.currentRow) return {}
  return props.detailSchema.reduce(
    (acc, schema) => {
      const value = props.currentRow[schema.field]
      acc[schema.field] = schema.formatter ? schema.formatter(value, props.currentRow) : value
      return acc
    },
    {} as Record<string, any>
  )
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  if (!elForm) {
    console.error('Form is not initialized')
    return null
  }
  const formData = await getFormData()

  // 合并 detailSchema 和 formSchema 中的所有属性
  const mergedData = {
    ...formattedData.value,
    ...formData
  }

  console.log('mergedData=', mergedData)
  return mergedData
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Descriptions :schema="detailSchema" :data="formattedData" />
  <Form @register="formRegister" :schema="formSchema" />
</template>
